package com.cskaoyan.controller;

import com.cskaoyan.bean.Admin;
import com.cskaoyan.bean.BaseRespVo;
import com.cskaoyan.bean.UserInfo;
import com.cskaoyan.mapper.AdminMapper;
import com.cskaoyan.service.AdminAdminService;
import com.cskaoyan.service.AdminAuthService;
import com.cskaoyan.shiro.MallToken;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("admin/auth")
public class AuthController {
    @Autowired
    AdminAuthService adminAuthService;
    @Autowired
    AdminAdminService adminAdminService;
    //subject可以直接获取到session，并不需要传入request参数
    //登录失败也要有日志记录
    @PostMapping("login")
    @ResponseBody
    public BaseRespVo login(@RequestBody Map map) {
        String username = (String) map.get("username");
        String password = (String) map.get("password");
        Subject subject = SecurityUtils.getSubject();
        MallToken mallToken = new MallToken(username, password, "admin");
        try {
            subject.login(mallToken);
        } catch (AuthenticationException e) {
            adminAuthService.login(false,username);
            return BaseRespVo.fail("用户名或密码不正确");
        }
        //登录的具体业务 → shiro整合的时候
        boolean authenticated=subject.isAuthenticated();
        Serializable sessionId = null;
        if (authenticated) {
            sessionId = subject.getSession().getId();
            System.out.println(sessionId+" in controller");
            Session session = subject.getSession();
            //给session添加name属性，用于取到管理员账号名称
            session.setAttribute("name",username);
            int userId = adminAdminService.selectUserId(username);
            session.setAttribute("id",userId);
            adminAuthService.login(authenticated,username);
            return BaseRespVo.ok(sessionId);
        }
        
        return BaseRespVo.fail();
    }

    @ResponseBody
    @RequestMapping("info")
    public BaseRespVo info(String token){
        //shiro在做 → 获得user信息
        Subject subject = SecurityUtils.getSubject();
        int userId = (int) subject.getSession().getAttribute("id");
        //根据userId查询对应的信息
        Admin admin = adminAdminService.info(userId);
        Integer[] roleIds = admin.getRoleIds();
        
        UserInfo userInfo = adminAuthService.info(roleIds);
        userInfo.setAvatar("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
        userInfo.setName(admin.getUsername());
        ArrayList<String> roles = new ArrayList<>();
        userInfo.setRoles(roles);
        roles.add("超级管理员");
        for (Integer roleId : roleIds) {
            if (roleId == 1) {
                List<String> perms=new ArrayList<>();
                perms.add("*");
                userInfo.setPerms(perms);
            }
        }
        return BaseRespVo.ok(userInfo);
    }
    //存在的问题:由于演示系统退出后看不到请求以及返回的数据，
    //所以重定向页面没做好
    @RequestMapping("logout")
    @ResponseBody
    public BaseRespVo logout(Object object, HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String name = (String) request.getSession().getAttribute("name");
        adminAuthService.logout(name);
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        
        return BaseRespVo.ok();
    }

}
